package com.hengpeng.msls.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hengpeng.common.configuration.ConfigProvider;
import com.hengpeng.common.configuration.ConfigProviderFactory;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.ActivityType;
import com.hengpeng.itfinbase.en.RewardType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.activity.CreateShareRedPacketRequest;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinbase.persist.RewardRedpacket;
import com.hengpeng.msls.util.CommUtil;

/**
 * 微信活动控制器
 * 
 * @author weiyuan
 *
 */
@Controller
@RequestMapping("/activityCore")
public class ActivityCoreController extends BaseController {
    
    /**
     * 到期时间
     */
    private static Map<String, Long> phoneTimeMap = new HashMap<String, Long>();
    
    /**
     * 次数
     */
    private static Map<String, Integer> phoneNumMap = new HashMap<String, Integer>();
    
    public final static ConfigProvider<String> cp = ConfigProviderFactory
            .getInstance(Constant.HP_COMMON_PROPERTIES_FILEPATH);
    
    public String h5domain = cp.getConfigByPrimaryKey("weixin.h5domain");

    /**
     * <pre>
     * 转向获取红包
     * </pre>
     * 
     * @param request
     * @param response
     * @param hostRedPacketId
     *            分享者红包的id
     * @return
     */
    @RequestMapping(value = "/toGetRedPacket")
    public String toGetRedPacket(HttpServletRequest request, HttpServletResponse response, ModelMap map,
            Long hostRedPacketId) {
        /**
         * <pre>
         * 1,获取微信当前登录用户 
         * 2，手机号码校验当前用户是否已在本平台注册，已注册红包状态就是可用，未注册红包状态就是未激活
         * </pre>
         * 
         */
        RewardRedpacket hostRedPacket = serviceFactory.getPersistService().get(RewardRedpacket.class,hostRedPacketId);// 获取分享者要分享的红包
        /**
         * 获取分享的六级红包
         */
        RewardType[] rewardTypes = new RewardType[] { RewardType.SHARE_ONE_RED, RewardType.SHARE_TWO_RED,
                RewardType.SHARE_THREE_RED, RewardType.SHARE_FOUR_RED, RewardType.SHARE_FIVE_RED,
                RewardType.SHARE_SIX_RED };
        List<Reward> sharerewards = serviceFactory.getRewardService().findRewardByTypes(rewardTypes);
        /**
         * 随机生成分享红包金额
         */
        Reward reward = sharerewards.get(CommUtil.getRandom(sharerewards.size(), 0));
        while (true) {
            reward = sharerewards.get(CommUtil.getRandom(sharerewards.size(), 0));
            if(hostRedPacket.getMoney()<=500){
                map.put("res", "error");
                break;
            }
            if (Long.parseLong(reward.getRewardVal()) < hostRedPacket.getMoney()) {
                break;
            }
        }
        map.put("reward", reward);
        map.put("hostRedPacket", hostRedPacket);
        return "/page/shareredpacket/toGetRedPacket.jsp";
    }

    /**
     * 获取红包
     * 
     * @param request
     * @param response
     * @param map
     * @param mobile
     * @param hostRedPacketId
     * @param shareMoney
     * @return
     */
    @RequestMapping(value = "/doGetRedPacket")
    public String doGetRedPacket(HttpServletRequest request, HttpServletResponse response, ModelMap map, String mobile,
            Long hostRedPacketId, Long rewardId, Long rewardVal) {
        
        setPhoneAndNum(mobile);
        
        Integer nums = phoneNumMap.get(mobile);
        if(nums!=null && nums<5){
            CreateShareRedPacketRequest csRequest = new CreateShareRedPacketRequest();
            csRequest.setActivityType(ActivityType.REDPACKET_SHARE);
            csRequest.setMobile(mobile);
            csRequest.setHostRedPacketId(hostRedPacketId);
            csRequest.setRewardId(rewardId);
            csRequest.setTransType(TransCodeConstants.ActivityTransCode.CREATE_SHARE_REDPACKET);
            ResponseMessage responseMessage = serviceFactory.getPortActiveFactory().remoteTrans(csRequest);
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(responseMessage.getRespCode())) {
                nums = nums+1;
                phoneNumMap.put(mobile, nums);
                map.put("res", "success");
            } else {
                map.put("res", "error");
            }
        }else{
            map.put("res", "full");
        }
        map.put("rewardVal", rewardVal);
        map.put("mobile", mobile);
        map.put("h5domain", h5domain);
        return "/page/shareredpacket/toGetRedPacket.jsp";
    }
    
    
    /**
     * <pre>
     * 判断是否过期
     * </pre>
     * 
     * @param @return
     * @return Boolean
     * @throws
     */

    private static Boolean HasExpired(Long phone_time) {

        if (phone_time != null) {
            // 过期时间，允许有一定的误差，一分钟。获取时间消耗
            if (System.currentTimeMillis()>phone_time) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 设置号码和次数
     * @param mobile
     */
    private static void setPhoneAndNum(String mobile){
        Long phone_time = phoneTimeMap.get(mobile);
        // 首次调用获取
        if (phone_time != null) {
            // 如果过期，需要重新获取
            if (HasExpired(phone_time)) {
                // 获取
                phoneTimeMap.put(mobile, System.currentTimeMillis() + (24 * 60 * 60 *1000));
                phoneNumMap.put(mobile, 0);
            }
        } else {
            phoneTimeMap.put(mobile, System.currentTimeMillis() + (24 * 60 * 60 *1000));
            phoneNumMap.put(mobile, 0);
        }
    }
}